package com.lad.pdfdemo.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.lad.pdfdemo.component.ViewPDF;
import com.lad.pdfdemo.entity.Product;
import com.lad.pdfdemo.service.PdfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 参考  https://www.cnblogs.com/scuury/p/10093287.html
 * @author luheng
 * @create 2019/7/11
 */
@RestController
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @RequestMapping("/helloPdf")
    public void helloPdf(HttpServletResponse response) {
        Document document = new Document(PageSize.A4);
        try {
            PdfWriter.getInstance(document, response.getOutputStream());
            document.addTitle("example of PDF");
            document.open();
            document.add(new Paragraph("Hello World!"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            document.close();
        }
    }

    @RequestMapping("/pdf")
    public void pdf(HttpServletResponse response) {
        try {
            pdfService.createPDF(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //打印pdf
    @RequestMapping("/printPdf")
    public ModelAndView printPdf() throws Exception{
        Product product1 = new Product("产品一","cp01",120);
        Product product2 = new Product("产品一","cp01",120);
        Product product3 = new Product("产品一","cp01",120);
        List<Product> products = new ArrayList<>();
        products.add(product1);
        products.add(product2);
        products.add(product3);
        Map<String, Object> model = new HashMap<>();
        model.put("sheet", products);
        return new ModelAndView(new ViewPDF(), model);
    }
}
